package com.wpw.dream.httpclient;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

/**
 * 
 * 
 * Project Name：dream-test ClassName：LoginClient Description：
 * 
 * @author: wupengwei
 * @date: 2017年2月27日 下午3:04:59 note:
 *
 */
public class LoginClient {

	@Test
	public void loginTest() {
		CloseableHttpClient client = HttpClients.createDefault();

		HttpPost httpPost = new HttpPost("http://192.168.200.194:9091/login_submit.htm");

		List<NameValuePair> formparams = new ArrayList<NameValuePair>();

		formparams.add(new BasicNameValuePair("userName", "wupengwei"));
		formparams.add(new BasicNameValuePair("passWord", "12345678"));

		UrlEncodedFormEntity uefEntity;

		uefEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
		httpPost.setEntity(uefEntity);
		System.out.println("executing request " + httpPost.getURI());

		try {
			CloseableHttpResponse response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();

			System.out.println(EntityUtils.toString(entity));

			CloseableHttpResponse response2 = client
					.execute(new HttpGet("http://192.168.200.194:9091/activity_index.htm"));
			System.out.println(EntityUtils.toString(response2.getEntity()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void loginTest2() throws Exception {
		CloseableHttpClient client = HttpClients.createDefault();

		URI uri = new URIBuilder().setScheme("http").setHost("127.0.0.1").setPort(8091).setPath("login_submit.htm")
				.build();

		HttpPost httpPost = new HttpPost(uri);

		EntityBuilder entityBuilder = EntityBuilder.create();
		entityBuilder.setParameters(new BasicNameValuePair("userName", "wupengwei"),
				new BasicNameValuePair("passWord", "12345678"));

		httpPost.setEntity(entityBuilder.build());
		try {
			CloseableHttpResponse response = client.execute(httpPost);
			Header[] allHeaders = response.getAllHeaders();
			for (Header header : allHeaders) {
				String a = header.getName() + ":" + header.getValue();
				System.out.println(a);
			}
			// httpPost.abort();
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			System.out.println(statusCode);

			HttpEntity entity = response.getEntity();
			System.out.println(EntityUtils.toString(entity));
			response.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
		client.close();
	}

	@Test
	public void loginTest3() {
		CloseableHttpClient client = new DefaultHttpClient();

		HttpPost httpPost = new HttpPost("http://127.0.0.1:8091/login_submit.htm");

	}

	@Test
	public void getTest() {
		try {
			URI uri = new URIBuilder().setScheme("http").setHost("www.baidu.com").setPath("/search")
					.setParameter("q", "httpclient").setParameter("btnG", "Google Search").setParameter("aq", "f")
					.setParameter("oq", "").build();
			HttpGet httpget = new HttpGet(uri);
			System.out.println(httpget.getURI());
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void EntityTest() {
		CloseableHttpClient client = HttpClients.createDefault();

		HttpPost httpPost = new HttpPost("http://www.baidu.com");

		try {
			CloseableHttpResponse response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();
			BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(entity);
			httpPost.abort();
			System.out.println(EntityUtils.toString(bufferedHttpEntity));
			System.out.println("关闭后的entity的缓存" + bufferedHttpEntity.getContentLength());

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void ResponseHandlerTest() throws Exception {
		CloseableHttpClient client = HttpClients.createDefault();

		HttpGet get = new HttpGet("http://www.baidu.com");
		String execute = client.execute(get, new ResponseHandler<String>() {

			@Override
			public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
				return EntityUtils.toString(response.getEntity());
			}

		});
		System.out.println(execute);
	}

	@Test
	public void RequestConfigTest() throws ClientProtocolException, IOException {
		RequestConfig config = RequestConfig.custom().setConnectTimeout(1000).build();
		CloseableHttpClient client = HttpClients.createDefault();
		HttpGet get = new HttpGet("http://www.cnblogs.com/");
		get.setConfig(config);
		CloseableHttpResponse response = client.execute(get);

		System.out.println(EntityUtils.toString(response.getEntity()));
	}

	@Test
	public void abortTest() {
		CloseableHttpClient client = HttpClients.createDefault();

		HttpGet get = new HttpGet("http://www.cnblogs.com/");
		try {
			CloseableHttpResponse response = client.execute(get);
			get.abort();
			HttpEntity entity = response.getEntity();
			System.out.println(EntityUtils.toString(entity));

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@Test
	//get请求会自动重定向，状态码是重定向后的状态码
	public void redirectTest() throws URISyntaxException {
		CloseableHttpClient client = HttpClients.createDefault();

		HttpClientContext context = HttpClientContext.create();

		HttpGet get = new HttpGet("http://192.168.200.194:9091/activity_index.htm");
		try {
			CloseableHttpResponse response = client.execute(get, context);
			System.out.println("状态码：" + response.getStatusLine().getStatusCode());//状态码是404，是重定向后的状态码
			Header[] allHeaders = response.getAllHeaders();
			for (Header header : allHeaders) {
				System.out.println(header.getName() + ":" + header.getValue());
			}
			
			HttpHost targetHost = context.getTargetHost();
			List<URI> redirectLocations = context.getRedirectLocations();
			//重定向的地址
			URI resolve = URIUtils.resolve(get.getURI(), targetHost, redirectLocations);

			HttpEntity entity = response.getEntity();
			System.out.println(EntityUtils.toString(entity));

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Test
	//post请求不会自动重定向，状态码是302
	public void postRedirectTest() throws URISyntaxException {
		CloseableHttpClient client = HttpClients.createDefault();

		HttpClientContext context = HttpClientContext.create();

		HttpPost post = new HttpPost("http://192.168.200.194:9091/activity_index.htm");
		try {
			CloseableHttpResponse response = client.execute(post, context);
			int statusCode = response.getStatusLine().getStatusCode();
			System.out.println("状态码：" + statusCode);//状态码是302
			if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
				Header[] allHeaders = response.getAllHeaders();
				for (Header header : allHeaders) {
					System.out.println(header.getName() + ":" + header.getValue());
				}
			}
			Header[] headers = response.getHeaders("location");
			String value = headers[0].getValue();
			System.out.println("重定向地址是：" + value);
			HttpHost targetHost = context.getTargetHost();
			List<URI> redirectLocations = context.getRedirectLocations();//null
			URIUtils.resolve(post.getURI(), targetHost, redirectLocations);
			
			HttpEntity entity = response.getEntity();
			System.out.println(EntityUtils.toString(entity));

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public  void cookieTest() {
		
	}
}
